package org.gavin.core.utils;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.gavin.core.enums.CommonStatus;
import org.gavin.core.exception.JsonConvertException;

import java.io.IOException;

/**
 * JSONUtils
 *
 * @author grl
 * @date 2024/4/29
 */
@Slf4j
public class JsonUtils {

    /**
     * 全局通用的 JSON mapper
     */
    public static final ObjectMapper mapper = new ObjectMapper();

    static {
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
        mapper.registerModule(new JavaTimeModule());
    }
    /**
     *  通用的 类型转换方法
     * @param t
     * @param type
     * @param <T>
     * @param <R>
     * @return
     * @throws IOException
     */
    public static <T extends Object,R> R convert( T t ,Class<R> type){
        try{
            if(t instanceof String){
                return mapper.readValue((String)t, type);
            }else if(t instanceof Number){
                return (R)t;
            }
            return mapper.readValue((JsonParser) t, type);
        }catch (IOException e){
            log.error("JSON 转换异常 {} 参数 {} 转换成 {}",e.getMessage(),t,type,e);
            throw JsonConvertException.le(CommonStatus.JSON_CONVERT_FAILED);
        }
    }

    /**
     * json格式化
     * @param json
     * @return
     */
    public static String toJsonString(Object json) {
        try {
            return mapper.writeValueAsString(json);
        } catch (JsonProcessingException e) {
            log.error("toJsonString 转换异常 {} 参数 {} 转换成 {}",e.getMessage(),json,e);
            throw JsonConvertException.le(CommonStatus.JSON_CONVERT_FAILED);
        }
    }
}
